package com.fs.ibox_h.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * jdbc工具类
 */
public class JDBCUtil {
   static Properties props = new Properties();
   static{
        //加载db.properties文件
        InputStream in =  JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
       try {
           //加载到Properties集合中
           props.load(in);
           Class.forName(props.getProperty("driverClass"));
       } catch (IOException e) {
           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
   }

    /**
     * 获取一个连接对象
     * @return
     */
    public static Connection getConnection() throws SQLException {
        return  DriverManager.getConnection(props.getProperty("url"),props.getProperty("username"),props.getProperty("password"));
    }


    /**
     * 关闭资源
     */
    public static void close(ResultSet rs, PreparedStatement pstmt,Connection conn){
        try {
            if(rs != null) rs.close();
            if(pstmt != null) pstmt.close();
            if(conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static PreparedStatement createPreparedStatement(Connection conn,String sql,Object... parms) throws SQLException {
        PreparedStatement pstmt = null;
        pstmt = conn.prepareStatement(sql);
        //给?赋值
        if(parms != null  && parms.length > 0){
            for (int i = 0 ; i <parms.length;i++) {
                pstmt.setObject(i+1,parms[i]);
            }
        }
        return pstmt;
    }
    /**
     * 执行增删改的方法
     * @return
     */
    public static  int executeUpdate(String sql,Object... parms){
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtil.getConnection();
            //jdbc默认是开启自动提交
            //设置为手动提交
            //conn.setAutoCommit(false);
            pstmt =createPreparedStatement(conn,sql,parms);
            int row = pstmt.executeUpdate();
            // 提交事务
           //conn.commit();
            return row;
        } catch (SQLException e) {
            e.printStackTrace();
            //出现异常的时候,回滚事务
            /*try {
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }*/
        }finally {
            JDBCUtil.close(null,pstmt,conn);
        }
        return 0;
    }

    /**
     * 执行查询的方法
     * @return
     */
    public static <T>  List<T> executeQuery(String sql,Class<T> clazz,Object... parms){
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtil.getConnection();
            pstmt =createPreparedStatement(conn,sql,parms);
            return parseResultSet(pstmt.executeQuery(),clazz);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(null,pstmt,conn);
        }
        return null;
    }

    /**
     * 解析ResultSet
     *   返回值?
     *   参数?
     */
    public static <T> List<T> parseResultSet(ResultSet rs, Class<T> clazz) throws SQLException, IllegalAccessException, InstantiationException {
        List<T>  list = new ArrayList<>();
        if(rs == null){
           return null;
        }
        while(rs.next()){
            //反射
            T t = clazz.newInstance();
            //获取从父类继承的属性
            //1.得到clazz对应的类的父类的Class类型
            Class<? super T> superclass = clazz.getSuperclass();
            //判断父类不是Object
            if(superclass != Object.class){
                Field[] superFields = superclass.getDeclaredFields();
                for (Field field : superFields) {
                    field.setAccessible(true);
                    //约定: 属性名与列名一样: 使用别名
                    field.set(t,rs.getObject(field.getName()));
                    //找set方法赋值
                }
            }
            //获取本类属性
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                //约定: 属性名与列名一样: 使用别名
                //数据库获取的id 类型:  Long   Admin的id Integer
                //  Long  赋值给Integer  错误
                field.set(t,rs.getObject(field.getName()));
                //rs.getInt()
               /* if(field.getType() == String.class){
                    field.set(t,rs.getString(field.getName()));
                }else if(field.getType() == Integer.class){
                    field.set(t,rs.getInt(field.getName()));
                }else if(field.getType() == Double.class){
                    field.set(t,rs.getDouble(field.getName()));
                }*/
                //找set方法赋值
            }

                list.add(t);
        }
        return list;
    }
}
